<template>
  <div>
    <h1>上传照片墙</h1>
    <form @submit.prevent="uploadPhotos">
      <input id="imageInput" class="ipfile" type="file" name="image" @change="previewImages">
      <button type="submit">上传照片</button>
    </form>
    <div id="photoWall">
      <img v-for="image in uploadedImages" :key="image" :src="image" class="uploaded-image" @click="openPreview(image)">
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  props: {
    uploadedImages: {
      type: Array,
      required: true
    }
  },
  methods: {
    previewImages(event) {
      var input = event.target
      if (input.files && input.files.length > 0) {
        for (var i = 0; i < input.files.length; i++) {
          var reader = new FileReader()
          reader.onload = (function(image) {
            return function(e) {
              this.uploadedImages.push(e.target.result)
              console.log(this.uploadedImages, 'this.uploadedImages')
            }
          })(input.files[i])
          reader.readAsDataURL(input.files[i])
        }
      }
    },
    uploadPhotos() {
      var formData = new FormData()
      var imageInput = document.getElementById('imageInput')
      for (var i = 0; i < imageInput.files.length; i++) {
        formData.append('upload_file', imageInput.files[i])
        console.log(imageInput.files[i], 'imageInput.files[i]')
      }
      axios
        .post('https://mainssl.geekpark.net/api/v1/admin/images', formData)
        .then(response => {
          if (response.status === 200) {
            alert('照片上传成功！')
            // 将新上传的图片与已上传的图片合并
            var newImages = Array.from(imageInput.files).map(file => URL.createObjectURL(file))
            this.uploadedImages = this.uploadedImages.concat(response.data.image.url)
            console.log(this.uploadedImages, 'this.uploadedImages')
            console.log(newImages, 'newImages')
            console.log(response.data.image.url, 'response')
            this.$emit('photo-uploaded', this.uploadedImages)
          } else {
            alert('照片上传失败！')
          }
        })
        .catch(error => {
          console.log(error)
          alert('照片上传失败！')
        })
    },
    openPreview(image) {
      var previewWindow = window.open('', '_blank')
      previewWindow.document.write('<img src="' + image + '">')
    }
  }
}
</script>

  <style scoped lang="scss">
  .ipfile {
    background: red;
  }

  #photoWall {
    display: flex;
  }

  .uploaded-image {
    width: 25%;
  }
  </style>
